<template>
  <div class="fullscreen-edit-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          <el-icon><Edit /></el-icon>
          知识库内容编辑
        </h1>
        <div class="breadcrumb-info">
          <span class="info-label">编辑条目：</span>
          <span class="item-title">{{ itemInfo.title }}</span>
          <el-tag v-if="itemInfo.knowledge_base_name" type="info" size="small" style="margin-left: 10px;">
            {{ itemInfo.knowledge_base_name }}
          </el-tag>
        </div>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">
          <el-icon><ArrowLeft /></el-icon> 返回列表
        </el-button>
        <el-button type="primary" :loading="saving" @click="saveContent">
          <el-icon><Check /></el-icon> 保存内容
        </el-button>
      </div>
    </div>

    <!-- 编辑内容区域 -->
    <div class="content-area">
      <el-form label-width="100px" class="edit-form">
        <el-form-item label="条目摘要">
          <el-input
            v-model="itemInfo.summary"
            type="textarea"
            rows="2"
            placeholder="请输入条目摘要，有助于搜索和理解"
          />
        </el-form-item>
        <el-form-item label="详细内容" required>
          <div class="editor-wrapper">
            <div class="wang-editor-container">
              <Toolbar
                class="wang-toolbar"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
              />
              <Editor
                class="wang-editor"
                v-model="content"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
                @onChange="handleChange"
              />
            </div>
            <div class="editor-tips">
              <p><strong>编辑功能：</strong></p>
              <ul>
                <li>支持富文本编辑</li>
                <li>支持插入图片、表格</li>
                <li>支持代码块、链接</li>
                <li>支持标题、列表、引用</li>
                <li>Ctrl+S 快速保存</li>
                <li>支持撤销/重做</li>
              </ul>
              <p><strong>提示：</strong></p>
              <ul>
                <li>内容会自动保存为HTML格式</li>
                <li>建议先在工具栏预览效果</li>
                <li>图片建议使用网络链接</li>
              </ul>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, shallowRef, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Check, Edit } from '@element-plus/icons-vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import {
  getKnowledgeItem, updateKnowledgeItem, getKnowledgeBases
} from '@/api/knowledge'

defineOptions({
  name: 'KnowledgeContentEdit'
})

const route = useRoute()
const router = useRouter()
const saving = ref(false)
const content = ref('')
const originalContent = ref('')
const editorRef = shallowRef()

// 编辑器配置
const toolbarConfig = {
  excludeKeys: ['fullScreen'] // 排除全屏功能
}

const editorConfig = {
  placeholder: '请输入知识条目的详细内容...',
  autoFocus: false,
  scroll: true,
  height: 300,
  MENU_CONF: {
    // 配置上传图片
    uploadImage: {
      server: '/api/upload', // 你的图片上传接口
      maxFileSize: 2 * 1024 * 1024, // 2M
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      meta: {
        token: 'xxx',
      },
      withCredentials: true,
      timeout: 5 * 1000, // 5秒
    }
  }
}

const itemInfo = reactive({
  id: null,
  title: '',
  summary: '',
  knowledge_base_id: '',
  knowledge_base_name: '',
  status: 1,
  priority: 5
})

// 获取知识库信息
const fetchKnowledgeBases = async () => {
  try {
    const res = await getKnowledgeBases({ skip: 0, limit: 100 })
    const bases = res.data || []
    const currentBase = bases.find(b => b.id == itemInfo.knowledge_base_id)
    if (currentBase) {
      itemInfo.knowledge_base_name = currentBase.name
    }
  } catch (e) {
    console.error(e)
  }
}

// 重置数据状态
const resetData = () => {
  content.value = ''
  originalContent.value = ''
  Object.assign(itemInfo, {
    id: null,
    title: '',
    summary: '',
    knowledge_base_id: '',
    knowledge_base_name: '',
    status: 1,
    priority: 5
  })
}

// 获取条目详情
const fetchItemDetail = async () => {
  try {
    const itemId = route.params.itemId
    if (!itemId) {
      ElMessage.error('条目ID不存在')
      goBack()
      return
    }

    // 重置数据状态
    resetData()

    const res = await getKnowledgeItem(itemId)
    const item = res.data

    if (!item) {
      ElMessage.error('条目不存在')
      goBack()
      return
    }

        Object.assign(itemInfo, item)
    content.value = item.content || ''
    originalContent.value = content.value

    // 确保编辑器内容也更新
    if (editorRef.value) {
      editorRef.value.setHtml(content.value)
    }

    await fetchKnowledgeBases()
  } catch (e) {
    console.error(e)
    ElMessage.error('获取条目详情失败')
    goBack()
  }
}

// 保存内容
const saveContent = async () => {
  if (!content.value.trim()) {
    ElMessage.error('请输入内容')
    return
  }

  saving.value = true
  try {
    const data = new URLSearchParams()
    data.set('content', content.value)
    data.set('summary', itemInfo.summary || '')

    await updateKnowledgeItem(itemInfo.id, data)
    originalContent.value = content.value
    ElMessage.success('保存成功')
  } catch (err) {
    console.error(err)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 返回列表
const goBack = () => {
  if (content.value !== originalContent.value) {
    ElMessageBox.confirm('内容已修改，确认离开吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确认离开',
      cancelButtonText: '继续编辑'
    }).then(() => {
      router.push({ name: 'KnowledgeItems' })
    }).catch(() => {})
  } else {
    router.push({ name: 'KnowledgeItems' })
  }
}

// 编辑器事件处理
const handleCreated = (editor) => {
  editorRef.value = editor
}

const handleChange = () => {
  // 可以在这里处理内容变化
}

// 快捷键保存
const handleKeydown = (e) => {
  if (e.ctrlKey && e.key === 's') {
    e.preventDefault()
    saveContent()
  }
}

// 监听路由参数变化，重新获取数据
watch(() => route.params.itemId, async (newItemId, oldItemId) => {
  if (newItemId && newItemId !== oldItemId) {
    await fetchItemDetail()
  }
})

onMounted(() => {
  fetchItemDetail()
  document.addEventListener('keydown', handleKeydown)
})

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor) {
    editor.destroy()
  }
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.fullscreen-edit-container {
  height: 100vh; /* 全屏高度 */
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa; /* 浅灰色背景 */
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-left: 10px;
}

.breadcrumb-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.info-label {
  font-weight: bold;
  color: #606266;
  margin-right: 8px;
}

.item-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.content-area {
  flex: 1;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow-y: auto; /* 允许内容区域滚动 */
}

.edit-form {
  width: 100%;
  max-width: 1200px; /* 最大宽度 */
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow: hidden;
}

.editor-wrapper {
  display: flex;
  gap: 20px;
  height: calc(100vh - 350px); /* 动态计算高度，减去头部和表单的高度 */
}

.wang-editor-container {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
  min-height: 500px;
  background-color: #fff;
}

.wang-toolbar {
  border-bottom: 1px solid #dcdfe6 !important;
  background-color: #fafafa;
}

:deep(.w-e-text-container) {
  height: calc(100vh - 450px) !important; /* 调整编辑区域高度 */
  min-height: 400px !important;
}

:deep(.w-e-scroll) {
  height: 100% !important;
}

.editor-tips {
  width: 300px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e1e6f0;
  max-height: calc(100vh - 350px);
  overflow-y: auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.editor-tips p {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 600;
}

.editor-tips ul {
  margin: 0 0 15px 0;
  padding-left: 20px;
  color: #909399;
  font-size: 13px;
}

.editor-tips li {
  margin-bottom: 6px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .editor-wrapper {
    flex-direction: column;
  }

  .editor-tips {
    width: 100%;
    max-height: 200px;
  }

  .wang-editor-container {
    min-height: 400px;
  }

  :deep(.w-e-text-container) {
    height: 300px !important;
  }
}

/* 头部按钮样式 */
.header-actions .el-button {
  margin-left: 10px;
}

.header-actions .el-button:first-child {
  margin-left: 0;
}

/* 页面标题图标样式 */
.page-title .el-icon {
  margin-right: 8px;
  color: #409eff;
}
</style>
